package com.dingpeikeji.quickdeer.mobile.service;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.CookieUtils;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.modules.cupons.entity.CuponsInfo;
import com.dingpeikeji.quickdeer.core.modules.cupons.service.TCuponsService;
import com.dingpeikeji.quickdeer.core.modules.line.entity.TLine;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.site.entity.TSitedtl;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Area;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Role;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.core.modules.sys.service.OfficeService;
import com.dingpeikeji.quickdeer.core.modules.sys.service.SystemService;
import com.dingpeikeji.quickdeer.mobile.web.MobileJsonController;
import com.dingpeikeji.quickdeer.modules.base.service.FrontUserService;
import com.dingpeikeji.quickdeer.modules.base.web.AuthUtil;
import com.dingpeikeji.quickdeer.modules.base.web.FSmsController;
import com.dingpeikeji.quickdeer.modules.base.web.FSysController;
import com.dingpeikeji.quickdeer.modules.realsche.service.FRealscheService;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ProRentOrders;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotype;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentgroup;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FRentproductService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductOrderService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentgroupService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentproductService;
import com.dingpeikeji.quickdeer.modules.sms.entity.Sms;
import com.dingpeikeji.quickdeer.modules.sms.service.CkeckTelephoneService;
import com.dingpeikeji.quickdeer.modules.sms.service.SmsApi;
import com.dingpeikeji.quickdeer.modules.utils.ValidateCodeTool;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.dingpeikeji.quickdeer.utils.BackResult;
import com.dingpeikeji.quickdeer.utils.JedisClient;
import com.dingpeikeji.quickdeer.utils.JsonUtils;
import com.dingpeikeji.quickdeer.utils.StringUtil;
import com.dingpeikeji.quickdeer.utils.UUIDUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import net.sf.json.JSONObject;

@Service
@Transactional(readOnly = true)
public class TravelProductService {
	@Autowired
	private TRentgroupService tRentgroupService;
	@Autowired
	private FRentproductService rentproductService;
	@Autowired
	private TSitedtlService tSitedtlService;
	@Autowired
	private RentproductOrderService rentproductOrderService;
	@Autowired
	private TRentproductService tRentproductService;
	@Autowired
	private FRealscheService fRealscheService;
	@Autowired
	private TCuponsService tCuponsService;
	@Autowired
	private OrderService orderService;

	// 热门旅游线路
	public BackResult getHotTravelList(TRentproduct tRentproduct, TRentgroup tRentgroup,HttpServletResponse response, 
			HttpServletRequest request,Model model) throws Exception {
		String type = request.getParameter("type");
		if ("wx".equals(type)) {//代表微信端的请求,获取城市名
			String cityName = ipLocation(request);
			tRentproduct.getDepartcity().setSitename(cityName);
		}
		//根据cityname查询对应的siteid
		String siteid = tSitedtlService.getSiteIdByName(tRentproduct.getDepartcity().getSitename());
		Map<String, Object> map = new HashMap<String, Object>();
		tRentgroup = initParam(tRentgroup, tRentproduct);// 初始化周边游,目的地游
		tRentgroup.setDepartcity(tRentproduct.getDepartcity());
		tRentgroup.setSiteid(siteid);
		tRentgroup.setSitename(tRentproduct.getDepartcity().getSitename());
		// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
		rentproductService.setCompAgreerateOffice(tRentproduct, request, "f");
		// 如果发车日期为空或者小于当前日期，则设置成明天,包车天数为空，1天-10天选择，默认1天
		tRentproduct.handleFromDate(model).handleDaysnum();
		tRentgroup.setIshot(request.getParameter("ishot"));
		//分页查询
		//List<TRentgroup> rentGroupList =tRentgroupService.getMobileTravelProducts(tRentgroup);
		List<TRentgroup> groupList =tRentgroupService.getMobileTravelProducts(tRentgroup);
		//没有查询到线路
		/*if(rentGroupList.size()==0||rentGroupList==null){
			//按照上海去查询
			tRentgroup.setTraveltype(1);
			tRentgroup.setSiteid(433+"");
			tRentgroup.setSitename("上海市");
			tRentgroup.setIshot(request.getParameter("ishot"));
			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(tRentproduct, request, "f");
			rentGroupList =tRentgroupService.getMobileTravelProducts(tRentgroup);
		}*/
		if(groupList.size()==0||groupList==null){
			//按照上海去查询
			tRentgroup.setTraveltype(1);
			tRentgroup.setSiteid(433+"");
			tRentgroup.setSitename("上海市");
			tRentgroup.setIshot(request.getParameter("ishot"));
			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(tRentproduct, request, "f");
			groupList =tRentgroupService.getMobileTravelProducts(tRentgroup);
		}
		List<TRentgroup> rentGroupList = new ArrayList<TRentgroup>();
		for (int i = 0; i < 4; i++) {
			rentGroupList.add(groupList.get(i));
		}
		// 查询线路对应的产品
		for (TRentgroup tr : rentGroupList) {
			tRentproduct.setDepartcity(tr.getDepartcity());
			tRentproduct.setDestcity(tr.getDestcity());
			tRentproduct.setProductname(tr.getProductname());
			tRentproduct.setRentType(tr.getRenttype());
			double lowestPrice = rentproductService.findLowestPrice(tRentproduct);
			tr.setLowestPrice(lowestPrice);
		}
		map.put("rentGroupList", rentGroupList);
		if (map.size()>0&&map!=null) {
			return BackResult.ok(map);
		}else{
			return BackResult.build("400", "霞客君太懒，您要的产品还没有上架。您可以试试定制包车哦");
		}
	}
	public static String ipLocation(HttpServletRequest request) throws IOException {
		String ip = request.getRemoteAddr();//获取ip
		String backUrl = "";
		if (ip.contains("0:0:0:0:0:0:0:1")||ip.contains("127.0.0.1")) {//本地
			backUrl = "https://api.map.baidu.com/location/ip?ak=pWa6dfvGtqEGvu1L2Mc2WGG1qBSlB8h9"
					+ "&coor=bd09ll";
		}else{
			backUrl = "https://api.map.baidu.com/location/ip?ak=pWa6dfvGtqEGvu1L2Mc2WGG1qBSlB8h9"
					+ "&coor=bd09ll&ip="+ip;
		}
        String result = AuthUtil.doGetString(backUrl);
        JSONObject jsonObject =  JSONObject.fromObject(result);  
        String string;
		try {
			string = jsonObject.getString("content");
		} catch (Exception e) {//定位失败
			return "常州市";
		}
        if (string!=null) {
        	JSONObject fromObject = jsonObject.fromObject(string);
        	String string2 = fromObject.getString("address_detail");
        	JSONObject fromObject2 = JSONObject.fromObject(string2);
        	String cityname = fromObject2.getString("city");
        	if (StringUtils.isNotEmpty(cityname)) {
        		return cityname;
        	}else{
        		return "常州市";
        	}
		}else{
			return "常州市";
		}
	}
	// 旅游线路
	public BackResult travelList(TRentproduct tRentproduct, TRentgroup tRentgroup, HttpServletRequest request,
			HttpServletResponse response,String pageNo,String pageSize,Model model,String destination,String estday) throws Exception {
		//根据sitenam查询对应的siteid
		String siteid = tSitedtlService.getSiteIdByName(tRentproduct.getDepartcity().getSitename());
		if (StringUtil.isEmpty(siteid)) {
			return BackResult.build("400", "未查询到数据");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		tRentgroup = initParam(tRentgroup, tRentproduct);// 初始化周边游,目的地游
		tRentgroup.setDepartcity(tRentproduct.getDepartcity());
		tRentgroup.setSiteid(siteid);
		tRentgroup.setSitename(tRentproduct.getDepartcity().getSitename());
		if ("0".equals(estday)||"不限".equals(estday)||StringUtils.isEmpty(estday)) {
			tRentgroup.setDaysnum(null);
		}else{
			tRentgroup.setDaysnum(Integer.parseInt(estday));
		}
		tRentgroup.setDestination(destination);
		// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
		rentproductService.setCompAgreerateOffice(tRentproduct, request, "f");
		// 如果发车日期为空或者小于当前日期，则设置成明天,包车天数为空，1天-10天选择，默认1天
		tRentproduct.handleFromDate(model).handleDaysnum();
		// 查询天数
		List<Integer> dayList = tRentgroupService.getTravelProductDaysNum(tRentgroup);
		List<String> daysList = new ArrayList<String>();
		for (Integer i : dayList) {
			daysList.add(i+"");
		}
		map.put("daysList", daysList);
		// 查询包含的景点
		Set<String> allSiteList = new TreeSet<String>();
		List<String> siteList = tRentgroupService.getTravelSiteList(tRentgroup);
		for (String sites : siteList) {
			String[] arr = sites.split("-");
			for (int i = 0; i < arr.length; i++) {
				allSiteList.add(arr[i]);
			}
		}
		map.put("allSiteList", allSiteList);
		//分页查询
		Page<TRentgroup> page = new Page<TRentgroup>(request, response);
		tRentgroup.setPage(page);
		page.setPageNo(Integer.parseInt(pageNo));
		page.setPageSize(Integer.parseInt(pageSize));
		List<TRentgroup> rentGroupList =tRentgroupService.getMobileTravelProducts(tRentgroup);
		//没有查询到线路
		if(rentGroupList.size()==0||rentGroupList==null){
			return BackResult.build("400", "霞客君太懒，您要的产品还没有上架。您可以试试定制包车哦");
		}
		page.setList(rentGroupList);
		// 查询线路对应的产品
		for (TRentgroup tr : rentGroupList) {
			tRentproduct.setDepartcity(tr.getDepartcity());
			tRentproduct.setDestcity(tr.getDestcity());
			tRentproduct.setProductname(tr.getProductname());
			tRentproduct.setRentType(tr.getRenttype());
			double lowestPrice = rentproductService.findLowestPrice(tRentproduct);
			tr.setLowestPrice(lowestPrice);
		}
		map.put("rentGroupList", rentGroupList);
		map.put("totalCount", page.getCount()+"");
		if (map.size()>0&&map!=null) {
			return BackResult.ok(map);
		}else{
			return BackResult.build("400", "霞客君太懒，您要的产品还没有上架。您可以试试定制包车哦");
		}
	}
	//旅游包车详情
	public BackResult travelDetails(TLine tLine) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		//获取线路描述
		String description = tRentgroupService.getDescriptionById(tLine.getLinename());
		description = description.replaceAll("&nbsp;", "");
		String[] arr = description.split("第"+"\\S"+"天");
		Map<String, String> descriptions = new HashMap<String, String>();
		List<Long> list = formatDesc(arr, descriptions);
		map.put("tLine", tLine);
		map.put("descriptions", descriptions);
		return BackResult.ok(map);
	}
	private List<Long> formatDesc(String[] arr, Map<String, String> map) {
		//el表达式中数字1是Long类型，无法匹配后台map中的int。
		//修改 map.put(0L, value);  前台 ：${map[1]}.
		List<Long> list = new ArrayList<Long>();
		long i = 1;
		for (String s : arr) {
			if (StringUtils.isEmpty(s)||s.length()==0||"".equals(s)) {
				continue;
			}
			map.put(i+"", s.substring(1).replaceAll(" {2,}", ""));//X{n,} X，至少 n 次
			i++;
			list.add(i);
		}
		return list;
	}
	private TRentgroup initParam(TRentgroup tRentgroup, TRentproduct tRentproduct) {
		if (tRentproduct.getTabType().contains("周边游包车")) {
			tRentproduct.setTabType("周边游包车");
			tRentproduct.setAnothertabType("目的地包车");
			tRentgroup.setTraveltype(1);
		} else if (tRentproduct.getTabType().contains("目的地包车")) {
			tRentproduct.setTabType("目的地包车");
			tRentproduct.setAnothertabType("周边游包车");
			tRentgroup.setTraveltype(2);
		} else {
			tRentgroup.setTraveltype(1);
			tRentproduct.setTabType("周边游包车");
			tRentproduct.setAnothertabType("目的地包车");
		}
		return tRentgroup;
	}
	public BackResult getCityByIp(HttpServletRequest request) throws IOException {
		String ip = request.getRemoteAddr();//获取ip
		String backUrl = "";
		if (ip.contains("0:0:0:0:0:0:0:1")||ip.contains("127.0.0.1")) {//本地
			backUrl = "https://api.map.baidu.com/location/ip?ak=pWa6dfvGtqEGvu1L2Mc2WGG1qBSlB8h9"
					+ "&coor=bd09ll";
		}else{
			backUrl = "https://api.map.baidu.com/location/ip?ak=pWa6dfvGtqEGvu1L2Mc2WGG1qBSlB8h9"
					+ "&coor=bd09ll&ip="+ip;
		}
        String result = AuthUtil.doGetString(backUrl);
        JSONObject jsonObject =  JSONObject.fromObject(result);  
        return BackResult.ok(jsonObject);
	}
	public BackResult travelBook(TRentproduct tRentproduct,String pageNo,String pageSize, Model model,TCargotype tCargotype,
			TRentgroup tRentgroup,TLine tLine,HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		// 如果发车日期为空或者小于当前日期，则设置成明天,包车天数为空，1天-10天选择，默认1天
		tRentproduct.handleFromDate(model).handleDaysnum();
		// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
		rentproductService.setCompAgreerateOffice(tRentproduct, request, "f");
		//获取车型
		String tstyle = request.getParameter("tstyle");
		tCargotype.setTstyles(tstyle);
		tRentproduct.setCargotype(tCargotype);
		//初始化TRentproduct
		tRentproduct.getDepartcity().setSiteid(tRentproduct.getDepartcity().getId());
		tRentproduct.getDestcity().setSiteid(tRentproduct.getDestcity().getId());
		tRentproduct.setProductname(tLine.getLinename());
		//初始化tcargotype
		tCargotype.getDepartcity().setSiteid(tRentproduct.getDepartcity().getId());
		tCargotype.getDestcity().setSiteid(tRentproduct.getDestcity().getId());
		tCargotype.setProductname(tLine.getLinename());
		// 分页对象
		Page<TCargotype> page = new Page<TCargotype>(request, response);
		page.setPageNo(Integer.parseInt(pageNo));
		page.setPageSize(Integer.parseInt(pageSize));
		tCargotype.setPage(page);
		//查询线路所拥有的车型
		List<TCargotype> cargotypeList = rentproductService.getCargotypeList(tCargotype);
		if (cargotypeList==null||cargotypeList.size()==0) {
			return BackResult.build("400", "未查询到数据");
		}
		page.setList(cargotypeList);
		tRentproduct.setCargotypeList(cargotypeList);
		//获取车型id,查询对应的线路报价
		List<TRentproduct> rentproductList = null;
		if (cargotypeList.size()>0) {
			for (TCargotype tc : cargotypeList) {
				tRentproduct.setCargotype(tc);
				rentproductList = rentproductService.findTravelMobileList(tRentproduct);
				tc.setRentproductList(rentproductList);
			}
		}
		// 整车查询列表
		map.put("cargotypeList", cargotypeList);
		map.put("totalCount", page.getCount()+"");
		return BackResult.ok(map);
	}
	//订单填写
	public BackResult genOrderDetails(TRentproduct tRentproduct, Model model, HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<String, Object>();
		// 根据ID查询选中的整车信息
		TRentproduct rentproduct = tRentproductService.get(tRentproduct.getRentid());
		TRentgroup rentgroup = tRentgroupService.getMobileRentgroup(rentproduct.getRentgrpid());
		if (rentproduct==null||rentgroup==null) {
			return BackResult.build("400", "参数有误");
		}
		// 协议价逻辑处理
		TRentproduct query = new TRentproduct();
		query.setRentid(tRentproduct.getRentid());
		if (StringUtils.isEmpty(tRentproduct.getTime())) {
			tRentproduct.setTime("06:00");//默认6点
		}
		query.setDepartdate(DateUtils.parseDate(tRentproduct.getFromdateStr() + " " + tRentproduct.getTime()));
		// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
		rentproductService.setCompAgreerateOffice(query, request, "f");
		query = rentproductService.getSuitrtnprice(query);
		rentproduct.setSuitrtnprice(query.getSuitrtnprice());
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);
		map.put("tRentproduct", rentproduct);
		map.put("rentgroup", rentgroup);
		map.put("iswifi", request.getParameter("iswifi"));
		map.put("powersupply", request.getParameter("powersupply"));
		map.put("tablewater", request.getParameter("tablewater"));
		map.put("businesssuit", request.getParameter("businesssuit"));
		map.put("paper", request.getParameter("paper"));
		return BackResult.ok(map);
	}
	/**
	 * 根据时间计算出当前的价格
	 */
	public void getOutFee(TRentproduct tRentproduct, HttpServletRequest request,HttpServletResponse response) throws Exception {
		// 根据ID查询选中的整车信息
		TRentproduct rentproduct = tRentproductService.get(request.getParameter("rentid"));
		if (rentproduct != null) {
			String cartypeName = rentproduct.getCargotype().getTypename();
			String outTimeFee = rentproduct.getCargotype().getOuttimefee()+"";
			String outKmsfee = rentproduct.getCargotype().getOutkmsfee()+"";
			String result = cartypeName+"#"+outTimeFee+"#"+outKmsfee;
			response.getWriter().println(result);
			return;
		}
		response.getWriter().println("未查询到数据");
	}
	/**
	 * 根据时间计算出当前的价格
	 */
	public BackResult getCurrentPrice(TRentproduct tRentproduct, HttpServletRequest request) throws Exception {
		// 根据ID查询选中的整车信息
		TRentproduct rentproduct = tRentproductService.get(tRentproduct.getRentid());
		if (rentproduct != null) {
			// 协议价逻辑处理
			TRentproduct query = new TRentproduct();
			query.setRentid(tRentproduct.getRentid());
			if (StringUtils.isEmpty(tRentproduct.getTime())) {
				tRentproduct.setTime("06:00");//默认6点
			}
			query.setDepartdate(DateUtils.parseDate(tRentproduct.getFromdateStr() + " " + tRentproduct.getTime()));
			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(query, request, "f");
			query = rentproductService.getSuitrtnprice(query);
			rentproduct.setSuitrtnprice(query.getSuitrtnprice());
			Double suitrtnprice = rentproduct.getSuitrtnprice();
			return BackResult.ok(suitrtnprice);
		}
		return BackResult.build("400", "参数错误");
	}
	/**
	 * 旅游包车生成订单
	 */
	public BackResult genOrderData(CuponsInfo cuponsInfo,TOrders orders, Model model,TRentgroup tRentgroup,
			HttpServletRequest request) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		TRentproduct tRentproduct = new TRentproduct();
		//手机端传入日期格式 2000-01-01 06:00
		String fromdateStr = request.getParameter("fromdateStr");
		String[] arr = fromdateStr.split("\\s");//按空格切割
		tRentproduct.setFromdateStr(arr[0]);
		tRentproduct.setTime(arr[1]);
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);
		//处理时间
		orders.setDepartdateStr(fromdateStr);
		// 消息集合
		List<String> messages = Lists.newArrayList(); // 消息
		orders.setDueamount(request.getParameter("totalPrice"));
		orders.setDetailAddress((request.getParameter("remark")));
		orders.setOrderuserid(request.getParameter("userid"));
		if (messages.isEmpty()) {
			// 协议价逻辑处理
			TRentproduct query = new TRentproduct();
			query.setRentid(Integer.parseInt(orders.getRealscheid()));
			query.setDepartdate(DateUtils.parseDate(orders.getDepartdateStr()));
			orders.setDepartdate(query.getDepartdate());//Fri Aug 25 06:00:00 CST 2017
			ProRentOrders pro = null;
			try {
				pro = rentproductOrderService.genOrder(orders);
				if (pro.success()) { // 如果成功生成订单，跳到支付方式选择页面
					Integer orderid = pro.getOrderid();
					orders.setOrderid(orderid+"");
					map.put("orders", orders);
					//改变优惠券使用状态
					if(StringUtils.isNotEmpty(cuponsInfo.getCuponsId())){
						CuponsInfo a = tCuponsService.getCuponsByRecordId(cuponsInfo.getCuponsId());
						if(Double.parseDouble(orders.getDueamount())+Double.parseDouble(cuponsInfo.getMoney())<Double.parseDouble(a.getMinPrice())){
							return BackResult.build("400", "提交失败");
				    	}
						orderService.updateOrderUseCupon(orders.getOrderid());
						cuponsInfo.setOrderId(orders.getOrderid());
						cuponsInfo.setUseTime(new Date());
						tCuponsService.useCupon(cuponsInfo);
					}
					return BackResult.ok(map);
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		return BackResult.build("400", messages.get(0));
	}
	//所有类型订单确定支付
	public BackResult pay(TOrders orders) throws Exception{
		// 校验数据
		fRealscheService.updateOrder(orders);
		orders = fRealscheService.getOrders(orders.getOrderid());
		if(!TOrders.STATUS_NO_PAY.equals(orders.getOrderstatus())){
			return BackResult.build("400", "该订单不可支付");
		}
		return BackResult.ok();
	}
}



























